//
//  DSTitleView.m
//  DemoTest
//
//  Created by DaShuEdu on 2017/5/12.
//  Copyright © 2017年 DaShuEdu. All rights reserved.
//

#import "DSTitleView.h"
#import "DSPageStyle.h"
#import "UIColor+DSColorRGB.h"

@interface DSTitleView ()

@property (nonatomic, strong) DSPageStyle *style;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, assign) NSInteger currentIndex;
@property (nonatomic, strong) UIColor *selectRGB;
@property (nonatomic, strong) UIColor *normalRGB;
@property (nonatomic, strong) UIColor *deltaRGB;
@property (nonatomic, strong) NSMutableArray  *titleLabels;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *bottomLine;
@property (nonatomic, strong) UIView *coverView;
@property (nonatomic, strong) UIView *upLine;
@property (nonatomic, strong) UIView *defaultLine;

@end

@implementation DSTitleView

- (instancetype)initWithFrame:(CGRect)frame
                        style:(DSPageStyle *)style
                       titles:(NSArray<NSString *> *)titles
{
    if (self = [super initWithFrame:frame]) {
        self.style = style;
        self.titles = titles;
        self.currentIndex = 0;
        self.titleLabels = [NSMutableArray arrayWithCapacity:5];
        [self setupUI];
    }
    return self;
}

#pragma mark - UI
- (void)setupUI {
    [self addSubview:self.scrollView];
    [self setupTitleLabels];
    [self setupLabelsFrame];
    [self setupBottomLine];
    [self setupCoverView];
    [self setLineWithUpDown];
}

- (void)setLineWithUpDown {
    CGFloat lineW = self.bounds.size.width;
    CGFloat lineH = self.style.defaultLineHeight;
    if (self.style.isShowUpLine) {
        self.upLine.frame = CGRectMake(0, 0, lineW, lineH);
        [self addSubview:self.upLine];
    }
    
    if (self.style.isShowDefaultLine) {
        self.defaultLine.frame = CGRectMake(0, self.bounds.size.height-lineH, lineW, lineH);
        [self addSubview:self.defaultLine];
    }
}

- (void)setupTitleLabels {
    for (int i = 0; i<self.titles.count; i++) {
        UILabel *label = [[UILabel alloc] init];
        label.text = self.titles[i];
        label.tag = i + 500;
        label.textColor = i == 0 ? self.style.selectColor : self.style.normalColor;
        label.font =  [UIFont systemFontOfSize:self.style.titleSize];
        label.textAlignment = NSTextAlignmentCenter;
        
        [self.scrollView addSubview:label];
        [self.titleLabels addObject:label];
        
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleLabelClick:)];
        [label addGestureRecognizer:tapGes];
        label.userInteractionEnabled = YES;
    }
}

- (void)setupLabelsFrame {
    CGFloat labelH = self.style.titleHeight;
    CGFloat labelY = 0;
    CGFloat labelW = 0;
    CGFloat labelX = 0;
    
    for (int i = 0; i<self.titleLabels.count; i++) {
        UILabel *titleLabel = self.titleLabels[i];
        if (self.style.isScrollEnable) {
            // 可以滚动
            labelW = [self.titles[i] boundingRectWithSize:CGSizeMake(MAXFLOAT, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : titleLabel.font} context:nil].size.width;
            labelX = i == 0 ? self.style.titleMargin * 0.5 : (CGRectGetMaxX(((UILabel *)self.titleLabels[i-1]).frame)+self.style.titleMargin);
        } else {
            // 不可以滚动
            labelW = self.bounds.size.width / (CGFloat)self.titleLabels.count;
            labelX = labelW * i;
        }
        
        titleLabel.frame = CGRectMake(labelX, labelY, labelW, labelH);
    }
    
    if (self.style.isScaleEnable) {
        UILabel *titleLabel = self.titleLabels.firstObject;
        titleLabel.transform = CGAffineTransformMakeScale(self.style.maxScale, self.style.maxScale);
    }
    
    if (self.style.isScrollEnable) {
        self.scrollView.contentSize = CGSizeMake(CGRectGetMaxX(((UILabel *)self.titleLabels.lastObject).frame)+self.style.titleMargin*0.5, self.bounds.size.height);
    }
}

- (void)setupBottomLine {
    if (!self.style.isShowBottomLine) {
        return;
    }
    [self.scrollView addSubview:self.bottomLine];
    
    CGRect bottomLineFrame = self.bottomLine.frame;
    bottomLineFrame.origin.x = ((UILabel *)(self.titleLabels.firstObject)).frame.origin.x;
    bottomLineFrame.size.width = ((UILabel *)(self.titleLabels.firstObject)).frame.size.width;
    self.bottomLine.frame = bottomLineFrame;
}

- (void)setupCoverView {
    if (!self.style.isShowCoverView) {
        return;
    }
    [self.scrollView insertSubview:self.coverView atIndex:0];
    
    UILabel *firstLabel = self.titleLabels.firstObject;
    CGFloat coverW = firstLabel.bounds.size.width;
    CGFloat coverH = self.style.coverHeight;
    CGFloat coverX = firstLabel.frame.origin.x;
    CGFloat coverY = (firstLabel.frame.size.height - coverH) * 0.5;
    
    if (self.style.isScrollEnable) {
        coverX -= self.style.coverMargin;
        coverW += 2 * self.style.coverMargin;
    }
    
    self.coverView.frame = CGRectMake(coverX, coverY, coverW, coverH);
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = self.style.coverRadius;
}

#pragma mark - Func
- (void)titleLabelClick:(UITapGestureRecognizer *)gesture {
    id targetLab = gesture.view;
    if (![targetLab isKindOfClass:[UILabel class]]) {
        return;
    }
    UILabel *targetLabel = targetLab;
    if (targetLabel.tag == self.currentIndex + 500) {
        return;
    }
    UILabel *sourceLabel = self.titleLabels[self.currentIndex];
    
    // 改变label的颜色
    sourceLabel.textColor = self.style.normalColor;
    targetLabel.textColor = self.style.selectColor;
    
    // 更新index
    self.currentIndex = targetLabel.tag - 500;
    [self adjustLabelPosition:targetLabel];
    if ([self.delegate respondsToSelector:@selector(titleViewWith:currentIndex:)]) {
        [self.delegate titleViewWith:self currentIndex:self.currentIndex];
    }
    
    if (self.style.isScaleEnable) {
        [UIView animateWithDuration:0.25 animations:^{
            sourceLabel.transform = CGAffineTransformIdentity;
            targetLabel.transform = CGAffineTransformMakeScale(self.style.maxScale, self.style.maxScale);
        }];
    }
    
    if (self.style.isShowBottomLine) {
        [UIView animateWithDuration:0.25 animations:^{
            CGRect bottomLineFrame = self.bottomLine.frame;
            bottomLineFrame.origin.x = targetLabel.frame.origin.x;
            bottomLineFrame.size.width = targetLabel.frame.size.width;
            self.bottomLine.frame = bottomLineFrame;
        }];
    }
    
    if (self.style.isShowCoverView) {
        CGFloat coverX = self.style.isScrollEnable ? (targetLabel.frame.origin.x - self.style.coverMargin) : targetLabel.frame.origin.x;
        CGFloat coverW = self.style.isScrollEnable ? (targetLabel.frame.size.width + self.style.coverMargin * 2) : targetLabel.frame.size.width;
        [UIView animateWithDuration:0.25 animations:^{
            CGRect coverViewFrame = self.coverView.frame;
            coverViewFrame.origin.x = coverX;
            coverViewFrame.size.width = coverW;
            self.coverView.frame = coverViewFrame;
        }];
    }
}

- (void)adjustLabelPosition:(UILabel *)targetLabel {
    if (!self.style.isScrollEnable) {
        return;
    }
    CGFloat offset = targetLabel.center.x - self.bounds.size.width * 0.5;
    
    if (offset < 0) {
        offset = 0;
    }
    if (offset > self.scrollView.contentSize.width - self.scrollView.bounds.size.width) {
        offset = self.scrollView.contentSize.width - self.scrollView.bounds.size.width;
    }
    
    [UIView animateWithDuration:0.25 animations:^{
        [self.scrollView setContentOffset:CGPointMake(offset, 0)];
    }];
}

#pragma mark - Lazy
- (UIColor *)deltaRGB {
    CGFloat deltaR = self.selectRGB.red - self.normalRGB.red;
    CGFloat deltaG = self.selectRGB.green - self.normalRGB.green;
    CGFloat deltaB = self.selectRGB.blue - self.normalRGB.blue;
    return [UIColor colorWithRed:deltaR green:deltaG blue:deltaB alpha:1.0];
}

- (UIColor *)selectRGB {
    return self.style.selectColor;
}

- (UIColor *)normalRGB {
    return self.style.normalColor;
}

- (UIScrollView *)scrollView {
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.scrollsToTop = NO;
    }
    return _scrollView;
}

- (UIView *)bottomLine {
    if (_bottomLine == nil) {
        CGRect frame = CGRectMake(0, self.bounds.size.height-self.style.bottomLineHeight, 0, self.style.bottomLineHeight);
        _bottomLine = [[UIView alloc] initWithFrame:frame];
        _bottomLine.backgroundColor = self.style.bottomLineColor;
    }
    return _bottomLine;
}

- (UIView *)coverView {
    if (_coverView == nil) {
        _coverView = [[UIView alloc] init];
        _coverView.backgroundColor = self.style.coverBgColor;
        _coverView.alpha = self.style.coverAlpha;
    }
    return _coverView;
}

- (UIView *)upLine {
    if (_upLine == nil) {
        _upLine = [[UIView alloc] init];
        _upLine.backgroundColor = self.style.defaultLineColor;
    }
    return _upLine;
}

- (UIView *)defaultLine {
    if (_defaultLine == nil) {
        _defaultLine = [[UIView alloc] init];
        _defaultLine.backgroundColor = self.style.defaultLineColor;
    }
    return _defaultLine;
}

#pragma mark - Delegate
- (void)contentViewWith:(DSContentView *)contentView inIndex:(NSInteger)inIndex
{
    self.currentIndex = inIndex;
    [self adjustLabelPosition:self.titleLabels[self.currentIndex]];
}

- (void)contentViewWith:(DSContentView *)contentView sourceIndex:(NSInteger)sourceIndex targetIndex:(NSInteger)targetIndex progress:(CGFloat)progress
{
    UILabel *sourceLabel = self.titleLabels[sourceIndex];
    UILabel *targetLabel = self.titleLabels[targetIndex];
    // 颜色渐变
    sourceLabel.textColor = [UIColor colorWithRed:(self.selectRGB.red - progress * self.deltaRGB.red) green:(self.selectRGB.green - progress * self.deltaRGB.green) blue:(self.selectRGB.blue - progress * self.deltaRGB.blue) alpha:1];
    targetLabel.textColor = [UIColor colorWithRed:(self.normalRGB.red + progress * self.deltaRGB.red) green:(self.normalRGB.green + progress * self.deltaRGB.green) blue:(self.normalRGB.blue + progress * self.deltaRGB.blue) alpha:1];
    
    if (self.style.isScaleEnable) {
        CGFloat deltaScale = self.style.maxScale - 1.0;
        sourceLabel.transform = CGAffineTransformMakeScale((self.style.maxScale - progress * deltaScale), (self.style.maxScale - progress * deltaScale));
        targetLabel.transform = CGAffineTransformMakeScale((1.0 + progress * deltaScale), (1.0 + progress * deltaScale));
    }
    
    if (self.style.isShowBottomLine) {
        CGFloat deltaX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x;
        CGFloat deltaW = targetLabel.frame.size.width - sourceLabel.frame.size.width;
        CGRect bottomLineFrame = self.bottomLine.frame;
        bottomLineFrame.origin.x = sourceLabel.frame.origin.x + progress * deltaX;
        bottomLineFrame.size.width = sourceLabel.frame.size.width + progress * deltaW;
        self.bottomLine.frame = bottomLineFrame;
    }
    
    if (self.style.isShowCoverView) {
        CGFloat deltaX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x;
        CGFloat deltaW = targetLabel.frame.size.width - sourceLabel.frame.size.width;
        CGRect coverViewFrame = self.coverView.frame;
        coverViewFrame.size.width = self.style.isScrollEnable ? (sourceLabel.frame.size.width + 2 * self.style.coverMargin + deltaW * progress) : (sourceLabel.frame.size.width + deltaW * progress);
        coverViewFrame.origin.x = self.style.isScrollEnable ? (sourceLabel.frame.origin.x - self.style.coverMargin + deltaX * progress) : (sourceLabel.frame.origin.x + deltaX * progress);
    }
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
